#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cassert>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <strings.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUFFER_NUM 1024

enum {
    SOCKET_ERR = 1,
    BIND_ERR,
    USAGE_ERR,
    SENDTO_ERR
};

class UdpClient
{
public:
    UdpClient(const std::string serverip, const uint16_t serverport):_serverip(serverip), _serverport(serverport)
    {}
    void init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socketfd == -1)
        {
            std::cerr << errno << ": "<< strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }
        //客户端不需要进行绑定
    }
    void run()
    {
        struct sockaddr_in server;
        // bzero(&server, sizeof(server));
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());
        server.sin_port = htons(_serverport);
        bool quit = false;
        while(!quit)
        {
            std::string msg;
            std::cout << "Your message: ";
            std::cin >> msg;
            int n = sendto(_socketfd, msg.c_str(), msg.size(), 0, (struct sockaddr*)&server, sizeof(server));
            if(n == -1)
            {
                std::cerr << errno << ": "<< strerror(errno) << std::endl;
                exit(SENDTO_ERR);
            }
            (void)n;
        }
        close(_socketfd);
    }
    ~UdpClient()
    {}
private:
    std::string _serverip;//点分十进制
    uint16_t _serverport;//服务端的端口
    int _socketfd;//打开的文件描述符
};